\section{CPU}
We have focused on writing readable code that is easy to understand and maintain. 
CPU instructions have been mapped to Haskell functions, and as a CPU by nature 
holds a state, the CPU will be represented as a reader monad transformer over 
a state thread (ST) monad. The reader environment contains the necessary 
registers simulated as variable equivalents, and functions for changing the 
state built as a small library on top. \\
\begin{code}
type CPU s a = ReaderT (CPUEnv s) (ST s) a
\end{code}

Since mapping low-level hardware instructions to high-level functions, the 
possibility of having a Domain Specific Embedded Language (DSEL) arises but 
we forwent this idea early on in the design process due to the fact that it 
would add more complexity to the code thus making the simulation slower.
The idea was to map the instructions to as basic as possible Haskell functions 
without sacrificing simplicity and readability.

\begin{code}
type Memory s = STArray s Address Operand

-- | CPU State that keeps track of registers and status flags.
data CPUEnv s = CPUState
   { aReg     :: STRef s Operand
   , xReg     :: STRef s Operand
   , yReg     :: STRef s Operand
   , sp       :: STRef s Word8
   , pc       :: STRef s Address
   , status   :: STRef s Operand
   , lowMem   :: Memory s    -- | Address range: 0    - 7FF
   , ppuMem   :: Memory s    -- | Address range: 2000 - 2007
   , uppMem   :: Memory s    -- | Address range: 4000 - FFFF
   , action   :: STRef s Action
   } 
\end{code}

\subsection{Modelling the Processor}
All Processors work at the same basic level; they fetch, decode and execute 
instructions. We try to encompass this inherent functionality but on a higher 
level using higher order functions, function composition and monads to increase 
readability and code simplicity.
\begin{code}
-- | Main CPU loop, fetches and executes instructions in order
loopCPU :: CPU s ()
loopCPU = do
    handleIRQ    
    fetch >>= execute
    loopCPU

-- | Fetches the address PC currently points to, and updates PC
fetch :: CPU s OPCode
fetch = do
    op <- getPC >>= readMemory
    alterPC (+1)
    return op 
\end{code}

Fetch works by extracting the current \textit{program counter} (PC) from the current 
state, reading the value contained at that memory location which is the current 
opcode to execute, altering the PC to point to the next instruction and finally 
returning the fetched opcode to be decoded and run by the execute function.
\begin{figure}[h!]
    \begin{center}
        \includegraphics[width=200px]{images/fetchex.png}
        \caption{Fetch/Execute cycle}
    \end{center}
\end{figure}

\begin{code}
 - | Decodes and Executes instructions
execute :: OPCode -> CPU s Int
execute op = case op of
    -- ADC
    0x69 -> immediate >>= adc >> return 2
    0x65 -> zeropage  >>= readMemory >>= adc >> return 3
    0x75 -> zeropageX >>= readMemory >>= adc >> return 4
    0x6D -> absolute  >>= readMemory >>= adc >> return 4
    0x7D -> absoluteX >>= readMemory >>= adc >> return 4
    0x79 -> absoluteY >>= readMemory >>= adc >> return 4
    0x61 -> indirectX >>= readMemory >>= adc >> return 6
    0x71 -> indirectY >>= readMemory >>= adc >> return 5 
    ...
\end{code}
Instruction decoding and execution is handled by a function conveniently named 
\textit{execute}, which basically is a big lookup function that translates opcodes 
to Haskell functions and also decodes the correct addressing mode for each 
instruction and returns the number of cycles it would take the real 2A03 to execute. 

The code snippet above shows mapping and decoding of the ADC instruction with all its 
addressing modes. \textit{ADC} stands for \textit{Add with Carry} and it adds 
the contents of the memory with the accumulator together with the carry bit 
from the status register. \\

Modeling 2A03 instructions to Haskell functions is a pretty straight forward 
process albeit slower since we are translating processor instructions to higher 
level code that will potentially be compiled to many instructions but we gain so 
much more in having a simple, readable and manageable code.
\begin{code}
-- | Logical AND
-- | A,Z,N = A&M
and :: Operand -> CPU s ()
and op = alterA (.&. op) >>= setZN                     
\end{code}
Example of how a Haskell function describing the \textit{AND} instruction is modeled. 
The contents of the A register is logically AND:ed with the decoded and fetched 
operand using the helper function \textit{alterA} to updated the register with the new 
result and finally binding this result to the \textit{setZN} function used to set the 
status register, in this case the \textit{zero} (Z) and \textit{negative} (N) 
flags respectively if the result was either zero or negative.
\begin{code}
setZN :: Operand -> CPU s ()
setZN op = setFlagZ (op == 0) >> setFlagN (op < 0)
\end{code}
